package com.taomeng.servlet.admin;

import com.taomeng.entity.PerDTree;
import com.taomeng.entity.RespBody;
import com.taomeng.service.PermissionService;
import com.taomeng.servlet.BaseServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@WebServlet("/per/*")
public class PermissionServlet extends BaseServlet {
    @Autowired
    private PermissionService permissionService;

    public void findPermissionsByRoleId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String roleId = req.getParameter("roleId");
        List<PerDTree> permissionList = permissionService.findPermissionByRoleId(roleId);

        RespBody respBody = new RespBody();
        respBody.setCode(200);
        respBody.setData(permissionList);

        RespBody.JsonObject(resp,respBody);
    }
    public void perDiaLog(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String roleId = req.getParameter("roleId");

        List<PerDTree> permissionByRoleId = permissionService.findPermissionByRoleId(roleId);
        List<String> permissions = permissionByRoleId.stream().map(PerDTree::getId).collect(Collectors.toList());


        req.setAttribute("permissions",permissions);
        req.setAttribute("roleId",roleId);
        req.getRequestDispatcher("/admin/public/perDialog.jsp").forward(req,resp);

    }
    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<PerDTree> dTreeList = permissionService.findAllPermission();

        for (PerDTree perDTree : dTreeList) {
            log.info(perDTree.toString());
        }
        RespBody respBody = new RespBody();
        respBody.setCode(200);
        respBody.setMsg("查询权限成功");
        respBody.setCount((long) dTreeList.size());
        respBody.setData(dTreeList);

        RespBody.JsonObject(resp, respBody);
    }

    @Override
    public void init() throws ServletException {
        super.init();
        ServletContext application = this.getServletContext();
        // 解决servlet用@Autowired自动注入service失败的问题
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, application);
    }
}
